import { createApp, Directive } from 'vue'
import Loading from './index.vue'

export const isEmptyObj = (obj: object): boolean => {
    return JSON.stringify(obj) === "{}"
}

const loading: Directive = {
    mounted(el, binding) {
        const app = createApp(Loading);
        const instance = app.mount(document.createElement('div')) as any;
        el.instance = instance;
        el.style.position = 'relative';
        const arg: any = binding.arg
        if (!isEmptyObj(arg as any)) {
            const params = {
                text: arg?.text || '加载中...',
                size: 'default'
            }
            instance.updateInfo(params)
        }
        if (binding.value) {
            appendFile(el);
        }
    },
    updated(el, binding) {
        if (binding.value !== binding.oldValue) {
            binding.value ? appendFile(el) : removeEl(el)
        }
    }
}
const appendFile = (el: { appendChild: (arg0: any) => void; instance: { $el: any; } }) => {
    el.appendChild(el.instance.$el)
}
const removeEl = (el: { removeChild: (arg0: any) => void; instance: { $el: any; } }) => {
    el.removeChild(el.instance.$el)
}
export default loading